.TH std::declval 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::declval \- std::declval

.SH Synopsis
   Defined in header <utility>
   template< class T >                                              \fI(since C++11)\fP
   typename std::add_rvalue_reference<T>::type declval() noexcept;

   Converts any type T to a reference type, making it possible to use member functions
   in the operand of the decltype specifier without the need to go through
   constructors.

   std::declval is commonly used in templates where acceptable template parameters may
   have no constructor in common, but have the same member function whose return type
   is needed.

   Note that std::declval can only be used in unevaluated contexts and is not required
   to be defined; it is an error to evaluate an expression that contains this function.
   Formally, the program is ill-formed if this function is odr-used.

.SH Parameters

   \fI(none)\fP

.SH Return value

   Cannot be called and thus never returns a value. The return type is T&& unless T is
   (possibly cv-qualified) void, in which case the return type is T.

.SH Possible implementation

   template<typename T>
   typename std::add_rvalue_reference<T>::type declval() noexcept
   {
       static_assert(false, "declval not allowed in an evaluated context");
   }

.SH Example


// Run this code

 #include <iostream>
 #include <utility>

 struct Default
 {
     int foo() const { return 1; }
 };

 struct NonDefault
 {
     NonDefault() = delete;
     int foo() const { return 1; }
 };

 int main()
 {
     decltype(Default().foo()) n1 = 1;                   // type of n1 is int
 //  decltype(NonDefault().foo()) n2 = n1;               // error: no default constructor
     decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int
     std::cout << "n1 = " << n1 << '\\n'
               << "n2 = " << n2 << '\\n';
 }

.SH Output:

 n1 = 1
 n2 = 1

.SH See also

   decltype specifier\fI(C++11)\fP obtains the type of an expression or an entity
   result_of                 deduces the result type of invoking a callable object with
   invoke_result             a set of arguments
   \fI(C++11)\fP(removed in C++20) \fI(class template)\fP
   \fI(C++17)\fP
